import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  // createWebHashHistory hash模式
  // import导入 meta元信息 env环境 BASE_URL 基准路径
  // import.meta 是ES6模块化文件自带的属性
  // env 是vite这个构建工具给当前项目追加的环境信息
  // BASE_URL：这个属性的值来自于 vite.config.ts文件中的base配置项
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('@/views/home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'article',
          component: () => import('@/views/article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: 'notice',
          component: () => import('@/views/notice/index.vue'),
          meta: { title: '消息通知' }
        },
        {
          path: 'user',
          component: () => import('@/views/user/index.vue'),
          meta: { title: '我的' },
          children: []
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/user/FamilyFile.vue'),
      meta: { title: '家庭档案' }
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/consult/ConsultFast.vue'),
      meta: {
        title: '选择医院类型'
      }
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/consult/consult-dep.vue'),
      meta: {
        title: '选择科室'
      }
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/consult/consult-illness.vue'),
      meta: {
        title: '图文问诊'
      }
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/consult/consult-pay.vue'),
      meta: {
        title: '支付问诊'
      }
    },
    {
      path: '/room',
      component: () => import('@/views/room/index.vue'),
      meta: {
        title: '问诊聊天室'
      },
      beforeEnter: (to, from) => {
        // reject the navigation
        return to.query.payResult === 'true'
      }
    },
    {
      path: '/user/consult',
      component: () => import('@/views/user/consult-page.vue'),
      meta: { title: '问诊记录' }
    }
  ]
})

// vue-router@4版本 ruturn值:
// 1. return 路径 跳转该路径
// 2. return true 方行
// 3. return undefined 放行
// 4. return false 阻止
router.beforeEach((to) => {
  const store = useUserStore()
  NProgress.start()
  // 1. 如果用户没有登录，前往的又不是登录页，强制前往登录页
  if (!store.user?.token && to.path != '/login') return '/login'
}),
  router.afterEach((to) => {
    document.title = '优医问诊-' + (to.meta.title || '')
    NProgress.done()
  })
export default router
